clear
clc
close all
% Listing 17.08 Creating an adjacency matrix
function A = grAdjacency( node, cost, dir )
 % compute an adjacency matrix.
% it should contain the weight from one
% node to another (0 if the nodes
% are not connected)
[m cols] = size(node);
n = length(cost);
k = 0;
% iterate across the edges
% finding the nodes at each end of the edge
for is = 1:n
iv = 0;
for ir = 1:m
for ic = 1:cols
if node(ir, ic) == is
iv = iv + 1;
if iv > 2
error('bad intersection matrix');
end
ij(iv) = ir;
end
end
end
if iv ~= 2
error(sprintf('didn’t find both ends of edge %d', is));
end
t = cost(is);
if dir(is) ~= -1
k = k + 1;
ip(k) = ij(1); jp(k) = ij(2); tp(k) = t;
end
if dir(is) ~= 1
k = k + 1;
ip(k) = ij(2); jp(k) = ij(1); tp(k) = t;
end
end
A = sparse( ip, jp, tp );
